package com.yeepay.skb.util;

import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.methods.multipart.StringPartTool;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SignUtil {

    public static String signHmac(Part[] parts,List<String> hmacArr) throws IOException {
//        Part[] parts=generateParams();
        String charSet="UTF-8";
//        List<String> hmacArr=needHmacArr();
        Map<String,StringPart> map=new HashMap<>();
        for(Part p:parts){
            if(p instanceof StringPart&&hmacArr.contains(p.getName())){//假如是字符类型
                map.put(p.getName(), (StringPart) p);
            }
        }
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        try {
            for(String name:hmacArr){
                StringPart sp=map.get(name);
                if (sp != null) {
                    new StringPartTool(sp).getValue(baos);
                    charSet=sp.getCharSet();
                }
            }
        } finally {
            baos.close();
        }
        String signature = new String(baos.toByteArray(),charSet);
        return Digest.hmacSign(signature, Conts.hmacKey);
    }
}
